package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.TestResult;
import com.itheima.domain.mongo.TestAnswer;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.TestSoulService;
import com.itheima.vo.TestRusultVo;
import com.itheima.vo.TestSoulVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class TestSoulManager {

    @DubboReference
    private TestSoulService testSoulService;

    @DubboReference
    private UserInfoService userInfoService;

    public ResponseEntity findTestSoul() {
        Long userId = UserHolder.get().getId();

        List<TestSoulVo> testSoulVos = testSoulService.findTestSoul(userId);

        return ResponseEntity.ok(testSoulVos);
    }

    public ResponseEntity commitTest(List<TestAnswer> testAnswers) {
        Long userId = UserHolder.get().getId();

        int score = 0;
        for (TestAnswer testAnswer : testAnswers) {
            score += testSoulService.getScore(testAnswer.getOptionId());

        }
        TestResult testRusult = new TestResult();
        List<Map> dimensions = new ArrayList<>();
        Map<String, String> map1 = new HashMap<>();
        map1.put("key", "外向");
        map1.put("value", RandomUtil.randomInt(60,99)+"%");
        dimensions.add(map1);

        Map<String, String> map2 = new HashMap<>();
        map2.put("key", "判断");
        map2.put("value", RandomUtil.randomInt(60,99)+"%");
        dimensions.add(map2);

        Map<String, String> map3 = new HashMap<>();
        map3.put("key", "抽象");
        map3.put("value", RandomUtil.randomInt(60,99)+"%");
        dimensions.add(map3);

        Map<String, String> map4 = new HashMap<>();
        map4.put("key", "理性");
        map4.put("value", RandomUtil.randomInt(60,99)+"%");
        dimensions.add(map4);

        testRusult.setDimensions(dimensions);

        String reportId = null;
        if (score < 21) {
            testRusult.setConclusion("猫头鹰：他们的共同特质为重计划、条理、细节精准。在行为上，表现出喜欢理性思考与分析、较重视制度、结构、规范。他们注重执行游戏规则、循规蹈矩、巨细靡遗、重视品质、敬业负责。");
            testRusult.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/owl.png");
            testRusult.setUserId(userId);
            testRusult.setType(1);

            reportId = testSoulService.saveTestResult(testRusult);
        } else if (score >= 21 && score <= 40) {
            testRusult.setConclusion("白兔型：平易近人、敦厚可靠、避免冲突与不具批判性。在行为上，表现出不慌不忙、冷静自持的态度。他们注重稳定与中长程规划，现实生活中，常会反思自省并以和谐为中心，即使面对困境，亦能泰然自若，从容应付。");
            testRusult.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/rabbit.png");
            testRusult.setUserId(userId);
            testRusult.setType(2);
            reportId = testSoulService.saveTestResult(testRusult);
        } else if (score >= 41 && score <= 55) {
            testRusult.setConclusion("狐狸型 ：人际关系能力极强，擅长以口语表达感受而引起共鸣，很会激励并带动气氛。他们喜欢跟别人互动，重视群体的归属感，基本上是比较「人际导向」。由于他们富同理心并乐于分享，具有很好的亲和力，在服务业、销售业、传播业及公共关系等领域中，狐狸型的领导者都有很杰出的表现。");
            testRusult.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/fox.png");
            testRusult.setUserId(userId);
            testRusult.setType(3);
            reportId = testSoulService.saveTestResult(testRusult);
        } else if (score >= 56) {
            testRusult.setConclusion("狮子型：性格为充满自信、竞争心强、主动且企图心强烈，是个有决断力的领导者。一般而言，狮子型的人胸怀大志，勇于冒险，看问题能够直指核心，并对目标全力以赴。他们在领导风格及决策上，强调权威与果断，擅长危机处理，此种性格最适合开创性与改革性的工作。");
            testRusult.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/lion.png");
            testRusult.setUserId(userId);
            testRusult.setType(4);
            reportId = testSoulService.saveTestResult(testRusult);
        }

        List<TestSoulVo> testSoulVos = testSoulService.findTestSoul(userId);

        Integer questionNum = testSoulService.getQuestionNum(testAnswers.get(0).getOptionId());

        if(questionNum == 1 ||questionNum == 2 ||questionNum == 3){
            for (TestSoulVo testSoulVo : testSoulVos) {
                if (testSoulVo.getStar() ==3) {
                    testSoulVo.setReportId(reportId);
                    testSoulService.saveTestSoul(testSoulVo,userId);
                }
                if (testSoulVo.getStar() ==4) {
                    testSoulVo.setIsLock(0);
                    testSoulService.saveTestSoul(testSoulVo,userId);
                }
            }
        }else if(questionNum == 4 ||questionNum == 5 ||questionNum == 6){
            for (TestSoulVo testSoulVo : testSoulVos) {
                if (testSoulVo.getStar() ==4) {
                    testSoulVo.setReportId(reportId);
                    testSoulService.saveTestSoul(testSoulVo,userId);
                }
                if (testSoulVo.getStar() ==5) {
                    testSoulVo.setIsLock(0);
                    testSoulService.saveTestSoul(testSoulVo,userId);
                }
            }
        }else {
            for (TestSoulVo testSoulVo : testSoulVos) {
                if (testSoulVo.getStar() ==5) {
                    testSoulVo.setReportId(reportId);
                    testSoulService.saveTestSoul(testSoulVo,userId);
                    break;
                }
            }
        }

        return ResponseEntity.ok(reportId);
    }

    public ResponseEntity getReport(String id) {
        TestResult testRusult = testSoulService.findResultById(id);
        TestRusultVo testRusultVo = new TestRusultVo();
        BeanUtil.copyProperties(testRusult, testRusultVo);

        Long userId = testRusult.getUserId();
        Integer type = testRusult.getType();

        List<TestResult> list = testSoulService.findResultByType(type);
        List<Map> similarYou = new ArrayList<>();

        for (TestResult result : list) {
            if (result.getUserId() != userId) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", result.getUserId());
                UserInfo userInfo = userInfoService.findByUserId(result.getUserId());
                map.put("avatar", userInfo.getAvatar());
                similarYou.add(map);
            }
        }

        Long userNum = 1L;
        while (similarYou.size() < 10) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", userNum);
            UserInfo userInfo = userInfoService.findByUserId(userNum);
            map.put("avatar", userInfo.getAvatar());
            similarYou.add(map);
            userNum++;
        }

        testRusultVo.setSimilarYou(similarYou);

        return ResponseEntity.ok(testRusultVo);
    }
}
